package com.cjzuji.rental.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cjzuji.rental.Bean.YoupinRequest;
import com.cjzuji.rental.Config.YpConfig;
import com.cjzuji.rental.controller.order.PassController;
import com.cjzuji.rental.controller.order.YouPinController;
import com.cjzuji.rental.dao.OrderBillDao;
import com.cjzuji.rental.dao.OrderContractDao;
import com.cjzuji.rental.dao.OrderDao;
import com.cjzuji.rental.dao.OrderUserDao;
import com.cjzuji.rental.mapper.OrderBillMapper;
import com.cjzuji.rental.mapper.OrderContractMapper;
import com.cjzuji.rental.mapper.OrderMapper;
import com.cjzuji.rental.mapper.OrderUserMapper;
import com.cjzuji.rental.pojo.Orders;
import com.cjzuji.rental.service.PassService;
import com.cjzuji.rental.service.YouPinService;
import com.cjzuji.rental.util.Tool;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@Service
public class PassServiceImpl implements PassService {
    @Autowired
    OrderDao orderDao;
    @Autowired
    OrderMapper orderMapper;
    @Autowired
    OrderUserMapper orderUserMapper;
    @Autowired
    OrderContractMapper orderContractMapper;
    @Autowired
    OrderUserDao orderUserDao;
    @Autowired
    OrderContractDao orderContractDao;
    @Autowired
    OrderBillDao orderBillDao;
    @Autowired
    YpConfig ypConfig;
    private static final Logger logger = LoggerFactory.getLogger(PassController.class);

    @Transactional
    @Override
    //http://127.0.0.1:9099/order/youpingpass/getPassInfo
    public List<Map<String, Object>> getPassList(String accesstoken, String authorization) {
        String url = ypConfig.getGetListUrl();
        System.out.println(url);
        YoupinRequest youpinRequest = new YoupinRequest();
        List<Map<String, Object>> listData = new ArrayList<>();
        youpinRequest.setModel("useList"); //查询租用中
        youpinRequest.setPageNo(0);
        youpinRequest.setPageSize(10);
        youpinRequest.setTransferMerchantTag(2);
        int pageNum = 0;  // 从第一页开始
        // 2. 转换为 JSON
        ObjectMapper objectMapper = new ObjectMapper();
        ObjectMapper resMapper = new ObjectMapper();
        ObjectMapper resDetailMapper = new ObjectMapper();
        ObjectMapper resUserMapper = new ObjectMapper();
        while (true) {
            try {
                youpinRequest.setPageNo(pageNum);
                String json = objectMapper.writeValueAsString(youpinRequest);
                String resStr = Tool.request(url,accesstoken,authorization,json,"", "");
                logger.info(resStr);
                Map<String,Object> res = resMapper.readValue(resStr,Map.class);
                // 获取 data → list
                Map<String, Object> dataMap = (Map<String, Object>) res.get("data");
                List<Map<String, Object>> list = (List<Map<String, Object>>) dataMap.get("list");
                if (list != null && list.size() > 0) {
                    for (Map<String, Object> item : list) {
                        //查询订单详情
                        String detail = ypConfig.getGetDetailUrl() + "?loanId=" + item.get("id");
                        String detailStr =  Tool.getRequest(detail,authorization,accesstoken, "");
                        Map<String,Object> resDel = resDetailMapper.readValue(detailStr,Map.class);
                        Map<String,Object> detailMap = (Map<String, Object>) resDel.get("data");
                        List<Map<String,Object>>  contractDtoList = (List<Map<String, Object>>) detailMap.get("contractDtoList");

                        //获取用户信息
                        String userUrl = ypConfig.getGetUserUrl();
                        List<String> userParam = new ArrayList<>();
                        userParam.add(item.get("receiverName").toString());  // 收货人名称
                        userParam.add(item.get("receiverMobile").toString());  //收货人手机
                        userParam.add(item.get("receiverAddressFormat").toString());  // 收货地址
                        userParam.add(item.get("mobile").toString());  //
                        userParam.add(item.get("idcardNo").toString());  //
                        userParam.add(null);  //
//                    logger.info("打印用户信息请求参数 {}",userParam);
                        //将参数转json
                        String userParamStr = objectMapper.writeValueAsString(userParam);
//                    logger.info("打印用户信息请求参数str {}",userParamStr);
                        String userRes =  Tool.request(userUrl,authorization,authorization,userParamStr,item.get("no").toString(), "");
                        Map<String,Object> resUser =  resUserMapper.readValue(userRes,Map.class);
                        List<String> userInfo = (List<String>) resUser.get("data");
                        String orderNo = item.get("no").toString();
                        logger.info("打印订单号 {}",orderNo);
                        Double actualFiancingAmount=(double)item.get("actualFiancingAmount");
                        Double buyoutAmount = (double)item.get("buyoutAmount");
                        Double monthRepayment = (double)item.get("renewMonthRepayment");
                        Double bondFreeCreditAmt = (double)item.get("frozenAmount");
                        String leaseTerm = item.get("termAndRenewTerm").toString();
                        String deliveryNo = item.get("orderNo").toString();
                        Double screenRisksAmount = (double)detailMap.get("realPayScreenRisksAmount");
                        String rentStartTime = item.get("rentStartDate").toString();
                        logger.info("打印开始时间 {}",rentStartTime);
                        String contractNo = contractDtoList.get(0).get("agreementCode").toString();
                        logger.info("打印合同编号 {}",contractNo);
                        String title = contractDtoList.get(0).get("title").toString();
                        logger.info("打印合同标题 {}",title);
                        String idcardImgUrl = detailMap.get("idcardImgUrl").toString();
                        String idcardBackImgUrl = detailMap.get("idcardBackImgUrl").toString();
                        String faceImgUrl = detailMap.get("faceImgUrl").toString();
                        // 遍历 list,根据优品的订单号查询 orders中的订单状态，如果orders中的订单状态 == 3 结束循环。
                        // orders中的状态如果 == 0 ,更新订单状态 =3 ,租用价格, 时间 ,租期
                        //从orders数据库拿到订单状态
                        orderMapper.upDataStatus(orderNo,actualFiancingAmount,buyoutAmount,monthRepayment,bondFreeCreditAmt,leaseTerm,deliveryNo,screenRisksAmount,rentStartTime);
                        orderContractMapper.upDataContract(orderNo,contractNo,title);
                        orderUserMapper.upDataUser(orderNo,idcardImgUrl,idcardBackImgUrl,faceImgUrl);
                    }
                }else {
                    break;
                }
                pageNum ++;
                logger.info("打印当前页码 {}",pageNum);
//                if (pageNum == 2) {
//                    break;
//                }
            } catch (JsonProcessingException e) {
                logger.info(e.getMessage());
                break;
            }
        }
        return listData;
    }

}
